//
//  UserLogin.m
//  Teacher
//
//  Created by 洋 耿 on 15/3/23.
//  Copyright (c) 2015年 ZengYuan. All rights reserved.
//

#import "UserLogin.h"
#import "Config.h"
#import "HTTP.h"
#import "UserUnit.h"

#import "ParentController.h"
#import "APService.h"

@implementation UserLogin
+(void)loginBy:(NSString *)phone andPwd:(NSString *)pwd
              success:(void (^)())success failure:(void (^)(NSString *error))failure{
    
    
    NSDictionary *dic = [[NSDictionary alloc] initWithObjects: @[phone,pwd] forKeys:@[@"phoneno", @"secret"]];
    
    NSString *json  =[dic JSONString];
    NSString *url = [NSString stringWithFormat:MAINURL,URL_LOGIN];
    
    [AWHttpTool post:url body:json success:^(id json) {
        
        NSString *msg = HTTPERROR_DATAFAIL;
        
        if (json) {
            
            NSInteger sta = [json[@"status"] integerValue];
            msg = json[@"msg"];
            NSLog(@"login status=%d msg=%@", sta, msg);
            
            if (sta == 0) {
                NSString *token = json[@"session_id"];
                NSString *user_id = json[@"user_id"];
                NSString *user_name = EMPTYSTRING_HANDLE(json[@"user_name"]);
                NSString *phoneno = EMPTYSTRING_HANDLE(json[@"phoneno"]);
                NSString *head_proto_url = EMPTYSTRING_HANDLE(json[@"head_proto_url"]);

                NSLog(@"session_id = %@",token);
                [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"session_id"];
                
                UserUnit *userunit =[[UserUnit alloc]init];
                userunit.useruuid   = user_id;
                userunit.userName   = user_name;
                userunit.userPasswd = pwd;
                userunit.userPhone  = phoneno;
                userunit.headImgUrl = head_proto_url;
                [UserUnit resetLoginUnit:userunit];
                
                [APService setAlias:userunit.useruuid callbackSelector:nil object:nil];
                success();

                return ;
            }
        }
        
        failure(msg);
        
    } failure:^(NSError *error) {
        failure(error.domain);
    }];

}
@end
